<?php
namespace app\api\controller;

use app\api\logic\Weixin;
use app\api\model\User;
use app\api\logic\File;

/**
 * @SWG\Swagger(
 * schemes={"http","https"},
 * host="weixin.v-yong.com/api",
 * consumes={"multipart/form-data"},
 * produces={"application/json"},
 * @SWG\Info(version="2.3", title="项目标题", description="项目描述"),
 * @SWG\Tag(name="Index", description="首页模块"),
 * @SWG\Tag(name="Weixin", description="微信模块"),
 * )
 */
class Index extends Base
{

    /**
     * @SWG\Post(
     * path="/index/index",
     * tags={"Index"},
     * summary="接口简介",
     * description="接口详细介绍",
     * @SWG\Parameter(name="mstr", description="加密KEY", in="formData", required=true, type="string"),
     * @SWG\Parameter(name="id", description="用户ID", in="formData", required=true, type="integer", default="1111"),
     *
     * @SWG\Response(
     * response=200,
     * description="成功返回数据",
     * @SWG\Header(header="id", type="integer", description="用户ID"),
     * @SWG\Header(header="openid", type="string", description="用户Openid")
     * )
     * )
     */
    
    /**
     * 接口首页 - 不能删除
     */
    public function Index()
    {
		echo 1111111;die;
        return $this->redirect('http://www.baidu.com');
    }

    public function wxNotify()
    {
        return 1;
    }

    /**
     * 公共上传单张图片接口，图片大小不能超过500KB，上传后图片会被缩略成500*500
     * 
     * @param  string    mstr
     * 
     * @return string
     */
    public function uploadImg()
    {
        $file = new File();
        $res = $file->uploadFile($this->accessData['aid'], 500000, 600, 600);
        
        if (isset($res['err_msg'])) {
            err($res['err_msg']);
        }
        
        suc('success', ['name'=>$res['name']]);
    }
    
    // 华德 - 创建红包
    public function createRedPackets()
    {
        $post = request()->only(['group_id', 'title', 'money', 'peoples'], 'post');
        
        // 调用微信支付 
        $data = [];
        $data['admin_id'] = $this->accessData['aid'];
        $data['user_id'] = $this->accessData['uid'];
        $data['subject'] = '创建红包';
        $data['amount'] = $post['money'];
        
        //创建订单
        $weixin = new Weixin();
        $payInfo = $weixin->unifiedOrder($data);
        
        if ( ! isset($payInfo['orderId'])) {
            err('微信订单成功失败');
        }
        
        $post['order_id'] = $payInfo['orderId'];
        $post['user_id'] = $this->accessData['uid'];
        $post['status'] = 0;
        $post['create_time'] = $this->timeStamp;
        
        $lastId = db('hx_red_packets')->insertGetId($post);
        
        if ($lastId <= 0) {
            err('创建红包失败');
        }
        
        suc('success', $payInfo);
    }
    
    // 华德 - 确认红包创建成功
    public function confirmCreateRedPackets()
    {
        $post = request()->only(['order_id'], 'post');
        
        // 测试
        $weixin = new Weixin();
        $res = $weixin->wxQueryOrder($this->accessData['aid'], $post['order_id']);
        
        if ($res['trade_state'] != 'SUCCESS') {
            err($res['trade_state_desc'], $res);
        }
        
        suc('支付确认成功', $res);
    }
    
    // 华德 - 领取红包
    public function getRedPackets()
    {
        $post = request()->only(['red_id'], 'post');
        
        $res = db('hx_red_packets')->where(['id'=>$post['red_id']])->find();
        
        if ( ! $res) {
            err('红包不存在');
        }
        
        // 红包金额是否够
        //$redCount = db('')
        
        // 文件锁 - 防止并发，导致红包多发
        $fp = fopen('uploads/lock_hdhx.txt', 'w+');
                
        if (!flock($fp, LOCK_EX | LOCK_NB)) {
            err('系统繁忙，请稍后再试！');
        }
        
        
    }
    
    // 获取红包领取记录
    public function getRedPacketsRecord()
    {
        $post = request()->only(['red_id', 'pagesize', 'page'], 'post');
        
        $result = $this->validate($post, 'Index.page');
        
        if (true !== $result) {
            err($result);
        }
        
        $field = 'u.nickname, u.avatarurl, log.money, log.create_time';
        
        $res = db('hx_red_packets_log')
            ->alias('log')
            ->field($field)
            ->join('user u', 'log.user_id = u.id')
            ->where(['red_id'=>$post['red_id']])
            ->page($post['page'], $post['pagesize'])
            ->select();
        
        if ( ! $res) {
            err('无领取记录');
        }
        
        suc('success', $res);
    }
}
